// 二次封装 axios  (拦截器)
import axios from "axios";
import ElementUI from "element-ui";
import {serveIP} from "../../public/config";

const request = axios.create({
    baseURL: 'http://'+ serveIP+':9090',
    /*baseURL: 'http://81.71.65.4:3003',*/
    timeout: 5000
})
request.interceptors.request.use((config) => {
        config.headers['Content-Type'] = 'application/json;charset=utf-8'

        let user = localStorage.getItem('user') ? JSON.parse(localStorage.getItem("user")):null
        if(user){
            config.headers['token'] = user.token;
        }
        return config;
    },
    (error) => {
        return Promise.reject(error);
    })


request.interceptors.response.use((response) => {
        // 接口响应时需要做的事
        let res = response.data
        //如果返回是文件
        if(response.config.responseType === 'blob'){
            return res
        }
        if(typeof res === 'String'){
            //是字符串返回JSON，否则原样返回
            res = res ? JSON.parse(res) : res
        }
        /*返回code编码判断*/
        if(res.code === '401'){
            /*引入ElementUI包  */
            ElementUI.Message({
                message: res.msg,
                type: 'error'
            })
        }
        return res
    },
    (error) => {
        // alert('网络错误!')
        console.log('err>>>>>>>>>>' + error)
        return Promise.reject(error)
    })

export default request


